package org.zjvis.datascience.common.util;

import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

import java.util.TimeZone;

/**
 * @description Spring容器工具类
 * @date 2021-09-15
 */
public class SpringUtil {

    private static ApplicationContext applicationContext;
    //0-2表示开发，测试，生产环境
    private static byte environ = 0;

    public static void setApplicationContext(ApplicationContext context) {
        SpringUtil.applicationContext = context;
        //获取当前的系统环境
        Environment evn = applicationContext.getEnvironment();
        String[] activeProfiles = evn.getActiveProfiles();
        for (String profile : activeProfiles) {
            if ("dev".equals(profile)) {
                break;
            } else if ("test".equals(profile)) {
                environ = 1;
                break;
            } else if ("prod".equals(profile)) {
                environ = 2;
                break;
            }
        }
        callbackAfterRunning();
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //获取配置文件配置值
    public static String getEvnProperty(String key) {
        return applicationContext.getEnvironment().getProperty(key);
    }


    //当前是否为开发环境
    public static boolean isDev() {
        return environ == 0;
    }

    //是否为测试环境
    public static boolean isTest() {
        return environ == 1;
    }

    //是否为生产环境
    public static boolean isProd() {
        return environ == 2;
    }

    ///获取当前环境
    public static byte getEnviron() {
        return environ;
    }

    private static void callbackAfterRunning() {
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
    }
}